<?php

namespace app\api\controller;


use app\api\model\Banner;
use app\api\model\Category;
use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Upload;
use OSS\Core\OssException;
use OSS\OssClient;
use think\Config;

/**
 * 公共接口
 */
class Common extends Api
{
    protected $noNeedLogin = ['init', 'captcha','Banner'];
    protected $noNeedRight = '*';

    public function _initialize()
    {

        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header('Access-Control-Expose-Headers: __token__');//跨域让客户端获取到
        }
        //跨域检测
        check_cors_request();

        if (!isset($_COOKIE['PHPSESSID'])) {
            Config::set('session.id', $this->request->server("HTTP_SID"));
        }
        parent::_initialize();
    }
    public function init()
    {
        $data['site']=Config::get("site");
        $this->success('',$data);
    }

    public function upload()
    {
        $file = $this->request->file('file');
        $upload = new Upload($file);
        $attachment = $upload->upload();
        $object = substr($attachment->url,1);
        $luj=dirname(dirname(dirname(dirname(__FILE__))))."/public";
        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
        $filePath =$luj.$attachment->url;
        $config = get_addon_config('alioss');
        try{
            $ossClient = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);

            $ossClient->uploadFile($config['bucket'], $object, $filePath);
        } catch(OssException $e) {
            printf(__FUNCTION__ . ": FAILED\n");
            printf($e->getMessage() . "\n");
            return;
        }
        $data['url']=$attachment->url;
        $this->success('请求成功',$data);

    }

    public function Banner()
    {
        $Banner = new Banner();
        $list=$Banner->order('weigh desc')->select();
        $this->success('',$list);
    }
    public function Category()
    {
        $type = $this->request->param('type');
        $Category = new Category();
        $where['type']=$type;
        $where['status']="normal";
        $list=$Category->where($where)->field('id,type,name')->order('weigh desc')->select();
        $this->success('',$list);
    }



}
